import React, { Component,Fragment} from 'react';
import {withRouter} from 'react-router-dom'
import { Form, Input, Button, Row, Col,message,Card} from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
//API
import {Login,GetAuthCode} from "../../api/account"
import {createFormData} from "../../utils/creatFormData"
//方法
import {setToken} from "../../utils/session"
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'

const initialPanes = [
    {title: '首页',icon: 'home',key: '/index'},
];

class LoginForm extends Component {
    state ={
        username: "",
        password: "",
        auth_code_base64:"",
        auth_code:""
    }
    //登录
    onFinish = (values) => { 
        const {username,password,auth_code} = this.state
        const user = {username:username,password:password,scope:auth_code}
        Login(createFormData({username,password,scope:auth_code})).then(response => {
            //console.log(response.data);
             //存储一下user 数据
            memoryUtils.user = user //保存到内存中,刷新浏览器丢失
            storageUtils.saveUser(user) //保存到local中
            storageUtils.saveTabs(initialPanes)
            storageUtils.saveActive_key(initialPanes[0].key)
            const {access_token} = response.data
            // console.log(token_type,access_token);
            //储存token
            setToken(access_token);
            message.success('登陆成功')
            this.props.history.push('/index');
        }).catch(error => {
            this.getAuthCode()
            console.log(error.response)
            if(error.response.data){
                if(error.response.data.detail.code=="101")
                    message.error("用户不存在")
                else if (error.response.data.detail.code=="102")
                    message.error("User is disable")
                else if (error.response.data.detail.code=="103")
                    message.error("密码错误")
                else if (error.response.data.detail.code=="108")
                    message.error("验证码错误")
                else
                    message.error(error.response)
            }
            else
                message.error(error.response)

        })
        // console.log('Received values of form: ', values);
    };
    //获取验证码
    getAuthCode = () =>{
        GetAuthCode().then(response => {
            console.log(response)
            this.setState({auth_code_base64:'data:image/png;base64,'+response.data.authcode_base64})
            console.log(this.state)
        }).catch(error =>{
            console.log(error)
        })
    }
    componentDidMount=()=>{
        //获取验证码
        this.getAuthCode()
    }

    toggleForm = () =>{
        this.props.switchForm('register');
    }
    inputChangeUser = (e) =>{
        let value = e.target.value
        this.setState({username:value})
    }
    inputChangePass = (e) =>{
        let value = e.target.value
        this.setState({password:value})
    }
    inputChangeAuth_code = (e) =>{
        let value = e.target.value
        this.setState({auth_code:value})
    }
    render() {
        const {username,password,auth_code} = this.state
        
        //  console.log(username,password)
        return (
            <div >
                <div className="form-header">
                        <h4 className="column">登录</h4>
                        <span onClick={this.toggleForm}>账号注册</span>
                </div>
                <Card hoverable>
                    
                    <Form
                        name="normal_login"
                        className="login-form"
                        initialValues={{ remember: true }}
                        onFinish={this.onFinish}
                        >
                        <p className="name">船员识别后台管理系统</p>
                        <Form.Item name="username"  rules={
                            [
                                { required: true, message: '请输入你的用户名!' }
                            ]
                        }>
                            <Input value={username} onChange={this.inputChangeUser} prefix={<UserOutlined className="site-form-item-icon" />} type="username" placeholder="请输入用户名" />
                        </Form.Item>
                       
                        <Form.Item name="password" rules={
                            [
                                { required: true, message: '密码不能为空！' },
                                // {pattern: validate_password,message:"请输入大于6位小于20位数字+字母"},
                            ]
                        }>
                            <Input value={password} onChange={this.inputChangePass} prefix={<LockOutlined className="site-form-item-icon" />} type="password" placeholder="请输入密码"/>
                        </Form.Item>
                        
                        <Form.Item name="auth_code" rules={
                            [
                                { required: true, message: '验证码不能为空!' },
                                {len:4, message:'请输入长度为4位的验证码'}
                            ]
                            }>
                            <Row gutter={13}>
                            <Col  span={15}>
                                <Input value={auth_code} onChange={this.inputChangeAuth_code} prefix={<LockOutlined className="site-form-item-icon" />} placeholder="请输入验证码" />
                            </Col>
                            <Col  span={9}>
                                {/*<Button type="danger" onClick={this.getCode} block>获取验证码</Button>*/}
                                <img src={this.state.auth_code_base64} onClick={this.getAuthCode} width={"85%"}/>
                            </Col>                            
                            </Row>
                        </Form.Item>
                        <p style={{'text-align':'center'}}>【温馨提示】忘记密码请联系管理员！</p>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" className="login-form-button" block>登录</Button>
                        </Form.Item>
                    </Form>
                </Card>
            </div>
        )
    }
}
export default withRouter(LoginForm);